import { defineStore } from 'pinia'
import { getLoginAPI, getuserAPI, getRoleMenusByIdAPI } from '@/api';
import { ElMessage } from "element-plus"
import type { IaccountType } from "@/views/Login/types"
import Storage from '@/utils/Storeage';
import router from '@/router';
import { LOGIN_TOKEN, USER_MENUS } from '@/global/constants';

interface ILoginState {
  token: string;
  userInfo: any,
  menus: any
}

const useLoginStore = defineStore('login', {
  // 如何指定state的类型
  state: (): ILoginState => ({
    token: Storage.get(LOGIN_TOKEN) ?? '',
    userInfo: {},
    menus: Storage.get(USER_MENUS) ?? []
  }),
  actions: {
    async getLoginAction(account: IaccountType) {
      // 1.根据账号密码登录 获取 id
      const { data } = await getLoginAPI(account)
      this.token = data.token
      const id = data.id
      const name = data.name
      // 3.提示用户
      ElMessage({
        message: `${name}欢迎回来~`,
        type: 'success'
      });
      // 2.进行本地缓存
      Storage.set(LOGIN_TOKEN, data.token)
      // 2.根据用户id查询用户详情
      const userInfo = await getuserAPI(id)
      this.userInfo = userInfo.data
      // 3.根据角色查询用户菜单
      const userMenus = await getRoleMenusByIdAPI(id)
      this.menus = userMenus.data

      Storage.set(USER_MENUS, userMenus.data)

      router.push('/main')
    }
  },
  getters: {

  }
})

export default useLoginStore
